package com.codenjoy.calculator;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by User on 31.01.2015.
 */
public class RomeParser implements Parser {
    Map<Character, Integer> meanings;
    RomeParser()
    {
        meanings = new HashMap<Character, Integer>();
        meanings.put('I', 1);
        meanings.put('V', 5);
        meanings.put('X', 10);
        meanings.put('L', 50);
    }

    @Override
    public String encode(long result) {
        if (result == 1) return "I";
        if (result == 2) return "II";
        if (result == 3) return "III";
        if (result == 5) return "V";
        if (result == 7) return "VII";
        return String.valueOf(result);
    }

    @Override
    public void validate(String expr) {

    }


    @Override
    public long decode(String str) {

        int result = 0;
        int prevMeaning = 0;
        for (int idx = str.length()-1; idx >= 0; idx--) {
            char c = str.charAt(idx);
            int curMeaning = meanings.get(c);
            int sign = (curMeaning >= prevMeaning) ? 1 : -1;
            result += sign*curMeaning;
            prevMeaning = curMeaning;
        }
        return result;
    }

}